package org.alvin.i18n.newui;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.alvin.i18n.ui.Pinyin4jUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class I18nV2ServiceV2 {

    public   JSONObject tranfer(File vueFile, String fileName ,String callStr ) throws IOException {
        JSONObject res = new JSONObject();
        //找到文件中的内容，解析成三段
        String content = new String(Files.readAllBytes(Paths.get(vueFile.getAbsolutePath())), "utf-8");
        int templateStart = content.indexOf("<template");
        int templateEnd = content.lastIndexOf("</template>");
        int templateEndLength = "</template>".length();
        String templateContent = content.substring(templateStart, templateEnd + templateEndLength);
        String newTemplateContent = doTransferTemplate(templateContent, res, fileName,callStr);
        System.out.println("-------------------------------------------------------------------");

        int scriptStart = content.indexOf("<script");
        int scriptEnd = content.lastIndexOf("</script>");
        int scriptEndLength = "</script>".length();
        String scriptContent = content.substring(scriptStart, scriptEnd + scriptEndLength);
        String newScriptContent = doTransferScript(scriptContent, res, fileName,"this." + callStr);
//
        int styleStart = content.indexOf("<style");
        int styleEnd = content.lastIndexOf("</style>");
        int styleEndLength = "</style>".length();
        String stypeContent = "";
        if (styleStart != -1) {
            stypeContent = content.substring(styleStart, styleEnd + styleEndLength);
        }
        String gap1 = "";
        if(templateEnd + templateEndLength + 1 < scriptStart){
            gap1 = content.substring(templateEnd + templateEndLength + 1, scriptStart);
        }
        String gap2 = "";
        String gap3 = "";
        if (styleStart != -1) {
            if(fileName.equals("App")){
                System.out.printf("");
            }
            if(scriptEnd + scriptEndLength + 1 < styleStart){
                gap2 = content.substring(scriptEnd + scriptEndLength + 1, styleStart);
                if(styleEnd + styleEndLength + 1 <= content.length()){
                    gap3 = content.substring(styleEnd + styleEndLength + 1);
                }
            }
        }
        if(!res.isEmpty()){
            String newContent = newTemplateContent + gap1 + newScriptContent + gap2 + stypeContent + gap3;
            Files.write(Paths.get(vueFile.getAbsolutePath()), newContent.getBytes(StandardCharsets.UTF_8));
        }
//
//        System.out.println("--------------------------------替换后的结果----------------------------------");
//        System.out.println(newTemplateContent + newScriptContent + stypeContent);
//        System.out.println("--------------------------------需要翻译的内容----------------------------------");
//        System.out.println("字段结果:" + res);
        return res;

    }

    public    String doTransferScript(String scriptContent, JSONObject res, String fileName ,String callStr) {
        //根据注释拆分成多个
        //脚本注释有 2  // \n ; /* */
        String tmpText = scriptContent;
        List<JSONObject> contentList = Lists.newArrayList();
        int index;
        int lastIndex = -1;
        int lastLength = 0;
        do {
            index = tmpText.indexOf("/**");
            int oneStart = tmpText.indexOf("/*");
            int doubleXieGang = tmpText.indexOf("//");
            if (doubleXieGang == 1203) {
                System.out.printf("");
            }
            int type = -1;
            if (index != -1 && oneStart != -1 && doubleXieGang != -1) {
                int minIndex = Math.min(index, oneStart);
                minIndex = Math.min(minIndex, doubleXieGang);
                if (minIndex == index) {
                    type = 1;
                } else if (minIndex == oneStart) {
                    type = 2;
                } else {
                    type = 3;
                }
            } else if (index == -1 && oneStart == -1 && doubleXieGang == -1) {
                JSONObject contentJson = new JSONObject();
                contentJson.put("content", tmpText);
                contentJson.put("type", 1);
                contentList.add(contentJson);
                break;
            } else if (index == -1 && oneStart != -1 && doubleXieGang != -1) {
                int minIndex = Math.min(oneStart, doubleXieGang);
                if (minIndex == oneStart) {
                    type = 2;
                } else {
                    type = 3;
                }
            } else if (index != -1 && oneStart == -1 && doubleXieGang != -1) {
                int minIndex = Math.min(index, doubleXieGang);
                if (minIndex == index) {
                    type = 1;
                } else {
                    type = 3;
                }
            } else if (index == -1 && oneStart == -1 && doubleXieGang != -1) {
                type = 3;
                index = doubleXieGang;
            } else if (index != -1 && oneStart != -1) {
                int minIndex = Math.min(index, oneStart);
                if (minIndex == index) {
                    type = 1;
                } else {
                    type = 2;
                }
            }

            if (type == 1) {
                String commentsTmpText = tmpText.substring(index);
                lastIndex = commentsTmpText.indexOf("*/");
                if (lastIndex == -1) {
                    index = -1;
                } else {
                    lastIndex = index + lastIndex;
                    lastLength = "*/".length();
                }
            } else if (type == 2) {
                String commentsTmpText = tmpText.substring(oneStart);
                lastIndex = commentsTmpText.indexOf("*/");
                if (lastIndex == -1) {
                    index = -1;
                } else {
                    lastIndex = oneStart + lastIndex;
                    lastLength = "*/".length();
                    index = oneStart;
                }
            } else if (type == 3) {
                String commentsTmpText = tmpText.substring(doubleXieGang);
                lastIndex = commentsTmpText.indexOf("\n");
                if (lastIndex == -1) {
                    index = -1;
                } else {
                    lastIndex = doubleXieGang + lastIndex;
                    lastLength = "\n".length();
                    index = doubleXieGang;
                }
            }

            if (index == -1) {
                JSONObject contentJson = new JSONObject();
                contentJson.put("content", tmpText);
                contentJson.put("type", 1);
                contentList.add(contentJson);
                break;
            }

            String content = tmpText.substring(0, index);
            JSONObject contentJson = new JSONObject();
            contentJson.put("content", content);
            contentJson.put("type", 1);
            contentList.add(contentJson);
            //
            String comments = tmpText.substring(index, lastIndex + lastLength);
            JSONObject commentsJson = new JSONObject();
            commentsJson.put("content", comments);
            commentsJson.put("type", 2);
            contentList.add(commentsJson);

            tmpText = tmpText.substring(lastIndex + lastLength);

        } while (tmpText.length() > 0);
        //找到中文
        for (JSONObject json : contentList) {
            if (json.getIntValue("type") == 2) {
                continue;
            }
            if (json.getString("content").indexOf("resetDividedInto") != -1) {
                System.out.println("--");
            }
            String replaceContent = transferScriptByText(json.getString("content"), res, fileName ,callStr);
            json.put("content", replaceContent);
        }
        StringBuilder sb = new StringBuilder();
        for (JSONObject json : contentList) {
            sb.append(json.getString("content"));
        }
        return sb.toString();
    }

    public   String transferScriptByText(String scriptContent, JSONObject res, String fileName ,String callStr) {
        //根据中文定位
        List<JSONObject> replaceRecord = Lists.newArrayList();
        String[] array = scriptContent.split("");
        if(fileName.equals("RechargeGiftDetail")){
            System.out.printf("");
        }

        hanziLabel:
        for (int i = 0; i < array.length; i++) {
            if (array[i].matches("[\\u4e00-\\u9fa5]")) {
                //确定类型，
                int startHanzi = i;
                //向回循环确定类型
                int backIndex = i;
                backLabel:
                for (int j = backIndex - 1; j >= 0; j--) {
                    //空格不处理
                    if (array[j].matches("\\s|\n|\t|\r")) {
                        continue;
                    }
                    if (array[j].equals("\"") || array[j].equals("'") || array[j].equals("`")) {
                        int startI = j;
                        while (true) {
                            i++;
                            int endI ;
                            if (i >= array.length) {
                                endI = i;
                                //替换中文字符
                                String text = scriptContent.substring(startI + 1, endI).trim();
                                String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                        HanyuPinyinVCharType.WITH_U_AND_COLON);
                                key = key.replaceAll("\\W", "");
                                JSONObject replaceJdon = new JSONObject();
                                replaceJdon.put("type", "replace");
                                replaceJdon.put("hanzi", text);
                                replaceJdon.put("start", startI);
                                replaceJdon.put("end", endI + 1);
                                String yinhao = "'";
                                if (array[j].equals("'")) {
                                    yinhao = "\"";
                                }
                                replaceJdon.put("content", callStr + "(" + yinhao + fileName + "." + key + yinhao + ")");
                                replaceRecord.add(replaceJdon);
                                res.put(key, text);
                                break backLabel;
                            }
                            if (array[i].equals(array[j]) && array[j].equals("`")) {
                                //表达式切分,然后改成前后格式化
//                                `第${i + 1}行数据和第${j + 1}行数据时间冲突`
                                endI = i;
                                String text = scriptContent.substring(startI + 1, endI).trim();
                                JSONObject replaceJdon = new JSONObject();
                                replaceJdon.put("type", "noReplace");
                                replaceJdon.put("hanzi", text);
                                replaceJdon.put("start", startI);
                                replaceJdon.put("end", endI + 1);
                                replaceJdon.put("content", "`"+text +"`");
                                replaceRecord.add(replaceJdon);
                                res.put("CustomKey:"+text, text);
                                break backLabel;
                            }
                            if (array[i].equals(array[j])) {
                                endI = i;
                                //替换中文字符
                                String text = scriptContent.substring(startI + 1, endI).trim();
                                String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                        HanyuPinyinVCharType.WITH_U_AND_COLON);
                                key = key.replaceAll("\\W", "");
                                JSONObject replaceJdon = new JSONObject();
                                replaceJdon.put("type", "replace");
                                replaceJdon.put("hanzi", text);
                                replaceJdon.put("start", startI);
                                replaceJdon.put("end", endI + 1);
                                String yinhao = "'";
                                if (array[j].equals("'")) {
                                    yinhao = "\"";
                                }
                                replaceJdon.put("content", callStr + "(" + yinhao + fileName + "." + key + yinhao + ")");
                                replaceRecord.add(replaceJdon);
                                res.put(key, text);
                                break backLabel;
                            }
                        }
                    }
                }
            }
        }
        //截取并替换
        StringBuilder sb = new StringBuilder(scriptContent);
        for (int i = replaceRecord.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = replaceRecord.get(i);
            sb.replace(jsonObject.getIntValue("start"), jsonObject.getIntValue("end"), jsonObject.getString("content"));
        }
        return sb.toString();
    }

    private   String doTransferTemplate(String templateContent, JSONObject res, String fileName,String callStr) {
        //1.根据注释拆分出多个内容
        List<JSONObject> contentList = Lists.newArrayList();
        String tmpText = templateContent;
        int index;
        do {
            index = tmpText.indexOf("<!--");
            int lastIndex = tmpText.indexOf("-->");
            int lastLength = 3;
            if (index == -1) {
                JSONObject contentJson = new JSONObject();
                contentJson.put("content", tmpText);
                contentJson.put("type", 1);
                contentList.add(contentJson);
                break;
            }

            String content = tmpText.substring(0, index);
            JSONObject contentJson = new JSONObject();
            contentJson.put("content", content);
            contentJson.put("type", 1);
            contentList.add(contentJson);
            //
            String comments = tmpText.substring(index, lastIndex + lastLength);
            JSONObject commentsJson = new JSONObject();
            commentsJson.put("content", comments);
            commentsJson.put("type", 2);
            contentList.add(commentsJson);

            tmpText = tmpText.substring(lastIndex + lastLength + 1);

        } while (tmpText.length() > 0);
        for (JSONObject json : contentList) {
            if (json.getIntValue("type") == 2) {
                continue;
            }
            String replaceContent = transferTemplateByText(json.getString("content"), res, fileName ,callStr);
            json.put("content", replaceContent);
        }
        StringBuilder sb = new StringBuilder();
        for (JSONObject json : contentList) {
            sb.append(json.getString("content"));
        }
        return sb.toString();
    }

    private   String transferTemplateByText(String content, JSONObject res, String fileName ,String callStr) {
        //2.内容替换分三种情况
        //>1 <  text="这里是中文">
        //>2 <>这里是中文<> --
        //>3 <  :text="test +'这里是中文'">
        List<JSONObject> replaceRecord = Lists.newArrayList();
        String[] array = content.split("");
        if(fileName.equals("TableView")){
            System.out.printf("");
        }
        hanziLabel:
        for (int i = 0; i < array.length; i++) {
            if (array[i].matches("[\\u4e00-\\u9fa5]")) {
                //确定类型，
                int startHanzi = i;
                //向回循环确定类型
                int backIndex = i;
                for (int j = backIndex - 1; j >= 0; j--) {
                    //空格不处理
                    if (array[j].matches("\\s|\n|\t|\r")) {
                        continue;
                    }
                    if (array[j].equals(">")) {
                        //向前走，并得到下一个<
                        int startI = i;
                        int endI = -1;
                        while (true) {
                            i++;
                            if (i >= array.length) {
                                endI = i;
                                break;
                            }
                            if (array[i].matches("\\s|\n|\t|\r")) {
                                continue;
                            }
                            if (array[i].equals("<") || (array[i].equals("{") && array[i+1].equals("{"))) {
                                endI = i;
                                break;
                            }
                        }
                        String text = content.substring(startHanzi, endI).trim();
                        String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                HanyuPinyinVCharType.WITH_U_AND_COLON);
                        key = key.replaceAll("\\W", "");
                        res.put(key, text);
                        //替换
                        JSONObject replaceJdon = new JSONObject();
                        replaceJdon.put("type", "replace");
                        replaceJdon.put("start", startHanzi);
                        replaceJdon.put("end", endI);
                        replaceJdon.put("hanzi", text);
                        replaceJdon.put("content", "{{ "+callStr+"('" + fileName + "." + key + "') }}");
                        replaceRecord.add(replaceJdon);
                        continue hanziLabel;
                    }
                    if(array[j].equals("`")){
                        int startI = i;
                        int endI = -1;
                        while (true) {
                            i++;
                            if (i >= array.length) {
                                endI = i;
                                break;
                            }
                            if (array[i].matches("\\s|\n|\t|\r")) {
                                continue;
                            }
                            if (array[i].equals("`")  ) {
                                endI = i;
                                break;
                            }
                        }
                        String text = content.substring(startHanzi, endI).trim();
                        String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                HanyuPinyinVCharType.WITH_U_AND_COLON);
                        key = key.replaceAll("\\W", "");
                        res.put(key, text);
                        //替换
                        JSONObject replaceJdon = new JSONObject();
                        replaceJdon.put("type", "replace");
                        replaceJdon.put("start", startHanzi);
                        replaceJdon.put("end", endI);
                        replaceJdon.put("hanzi", text);
                        replaceJdon.put("content",  "`"+text+"`");
                        replaceRecord.add(replaceJdon);
                        continue hanziLabel;
                    }
                    //引号要看看前面是什么
                    if (array[j].equals("\"") || array[j].equals("'")) {
                        //判断前面
                        for (int k = j - 1; k > 0; k--) {
                            if (array[k].matches("\\s|\n|\t|\r")) {
                                continue;
                            }
                            if (array[k].equals("+")) {
                                int startI = j;
                                //向前找到下一个引号 ，替换
                                for (int s = startHanzi; s < array.length; s++) {
                                    if (array[s].matches("\\s|\n|\t|\r")) {
                                        continue;
                                    }
                                    if (array[j].equals(array[s])) {
                                        int endI = s;
                                        //替换中文字符
                                        String text = content.substring(startI + 1, endI - 1).trim();
                                        String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                                HanyuPinyinVCharType.WITH_U_AND_COLON);
                                        key = key.replaceAll("\\W", "");
                                        JSONObject replaceJdon = new JSONObject();
                                        replaceJdon = new JSONObject();
                                        replaceJdon.put("type", "replace");
                                        replaceJdon.put("start", startI + 1);
                                        replaceJdon.put("end", endI);
                                        String yinhao = "'";
                                        if (array[j].equals("'")) {
                                            yinhao = "\"";
                                        }
                                        replaceJdon.put("content", callStr + "(" + yinhao + fileName + "." + key + yinhao + ")");
                                        replaceRecord.add(replaceJdon);
                                        res.put(key, text);

                                        i = endI;
                                        continue hanziLabel;
                                    }
                                }
                                continue;
                            }
                            if (array[k].equals("?") || array[k].equals(":") || array[k].equals("&") || array[k].equals("|") || array[k].equals("(") || array[k].equals("[") || array[k].equals("{")) {
                                int startI = startHanzi;
                                //向前找到下一个引号 ，替换
                                for (int s = startHanzi + 1; s < array.length; s++) {
                                    if (array[s].matches("\\s|\n|\t|\r")) {
                                        continue;
                                    }
                                    if (array[j].equals(array[s])) {
                                        System.out.println("---------");
                                        //替换中文字符
                                        int endI = s;
                                        String text = content.substring(startI, endI).trim();
                                        String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                                HanyuPinyinVCharType.WITH_U_AND_COLON);
                                        key = key.replaceAll("\\W", "");
                                        JSONObject replaceJdon = new JSONObject();
                                        replaceJdon = new JSONObject();
                                        replaceJdon.put("type", "replace");
                                        replaceJdon.put("start", startI);
                                        replaceJdon.put("end", endI);
                                        String yinhao = "'";
                                        if (array[j].equals("'")) {
                                            yinhao = "\"";
                                        }
                                        replaceJdon.put("content", "$t(" + yinhao + fileName + "." + key + yinhao + ")");
                                        replaceRecord.add(replaceJdon);
                                        res.put(key, text);
                                        i = endI;
                                        continue hanziLabel;
                                    }
                                }
                                System.out.println(array[k]);
                            }
                            if (array[k].equals("=")) {
                                //找到属性的开头
                                boolean hasZifu = false;
                                for (int s = k - 1; s > 0; s--) {
                                    if (array[s].matches("\\s|\n|\t|\r") && !hasZifu) {
                                        continue;
                                    }
                                    if (array[s].matches("\\s|\n|\t|\r") && hasZifu) {
                                        //查询结束
                                        int startI = j;
                                        for (int t = startHanzi + 1; t < content.length(); t++) {
                                            if (array[t].matches("\\s|\n|\t|\r")) {
                                                continue;
                                            }
                                            if (array[t].equals(array[j])) {
                                                int endI = t;

                                                //前面加冒号
                                                JSONObject replaceJdon = new JSONObject();
                                                replaceJdon.put("type", "insert");
                                                replaceJdon.put("start", s + 1);
                                                replaceJdon.put("end", s + 1);
                                                replaceJdon.put("content", ":");
                                                replaceRecord.add(replaceJdon);
                                                //替换中文字符
                                                String text = content.substring(startI + 1, endI).trim();
                                                String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                                        HanyuPinyinVCharType.WITH_U_AND_COLON);
                                                key = key.replaceAll("\\W", "");
                                                replaceJdon = new JSONObject();
                                                replaceJdon.put("type", "replace");
                                                replaceJdon.put("hanzi", text);
                                                replaceJdon.put("start", startI + 1);
                                                replaceJdon.put("end", endI);
                                                String yinhao = "'";
                                                if (array[j].equals("'")) {
                                                    yinhao = "\"";
                                                }
                                                replaceJdon.put("content", "$t(" + yinhao + fileName + "." + key + yinhao + ")");
                                                replaceRecord.add(replaceJdon);
                                                res.put(key, text);

                                                i = endI;
                                                continue hanziLabel;
                                            }
                                        }
                                        break;
                                    }
                                    hasZifu = true;
                                }
                            }
                        }

                    }
                    if (array[j].equals("}") && array[j-1].equals("}")){
                        while (true) {
                            i++;
                            if (i >= array.length) {
                                // 不考虑这种情况，这种情况应该是语法错误
                            }
                            if (array[i].matches("\\s|\n|\t|\r")) {
                                continue;
                            }
                            if(array[i].equals("<") || array[i].equals("{") ){
                                break ;
                            }
                        }
                        String text = content.substring(startHanzi, i).trim();
                        String key = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                                HanyuPinyinVCharType.WITH_U_AND_COLON);
                        key = key.replaceAll("\\W", "");
                        JSONObject replaceJdon = new JSONObject();
                        replaceJdon.put("type", "replace");
                        replaceJdon.put("hanzi", text);
                        replaceJdon.put("start", startHanzi );
                        replaceJdon.put("end", i);
                        replaceJdon.put("content", "{{ $t('" + fileName + "." + key + "') }}");
                        replaceRecord.add(replaceJdon);
                        res.put(key, text);
                        continue hanziLabel;
                    }
                }
            }
        }
        //替换目标内容
        StringBuilder sb = new StringBuilder(content);
        for (int i = replaceRecord.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = replaceRecord.get(i);
            if (jsonObject.getString("type").equals("insert")) {
                sb.insert(jsonObject.getIntValue("start"), ":");
            } else {
                sb.replace(jsonObject.getIntValue("start"), jsonObject.getIntValue("end"), jsonObject.getString("content"));
            }
        }
        return sb.toString();
    }
}
